<template>
  <div class="container-app">
    <div class="btn-group">
      <el-button v-if="hasAdd" size="small" type="success" @click="addLine"><i class="el-icon-plus"></i>{{addTitle}}</el-button>
      <el-button v-if="hasDel" size="small" type="danger" @click="removeLine"><i class="el-icon-delete"></i>{{delTitle}}</el-button>
      <el-button v-if="hasUpdate" size="small" type="primary" @click="changeLine"><i class="el-icon-edit-outline"></i>{{updateTitle}}</el-button>
      <span class="right-search">
        <el-input @change="findLine" v-model="menuSerData" size="small" placeholder="输入关键字搜索" style="width:300px;">
          <el-button @click="findLine" slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </span>
    </div>
    <tree-table @selectChange="choice" :data="tableData" :columns="columns" border></tree-table>

   <!--对话界面-->
    <el-dialog :title="title" :visible.sync="menuVisible" width="50%" :before-close="handleClose">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">
      	<el-form-item v-if="ismodelMenu == true" label="菜单名称" prop="name">
          <el-select v-model="ruleForm.name" size="small" @change="sletMenuName" style="width:80%" placeholder="请选择菜单名称">
            <el-option
              v-for="item in modelMenusList"
              :key="item.description"
              :label="item.description"
              :value="item.description">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-else label="菜单名称" prop="name">
          <!-- <el-input :disabled="isUpdate" size="small" v-model="ruleForm.name"></el-input> -->
          <el-input size="small" v-model="ruleForm.name" placeholder="请输入菜单名称"></el-input>
        </el-form-item>
        <el-form-item v-show="ismodelMenu" label="参数信息" prop="paras">
          <!-- <el-input :disabled="isUpdate" size="small" v-model="ruleForm.name"></el-input> -->
          <el-input size="small" v-model="ruleForm.menuparas" readonly></el-input>
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-select v-model="ruleForm.menuType" size="small" style="width:80%" placeholder="请选择菜单类型">
            <el-option
              v-for="item in menuType"
              :key="item.id"
              :label="item.label"
              :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单URL" prop="url">
          <el-input size="small" v-model="ruleForm.url" placeholder="请输入菜单url，没有可忽略"></el-input>
        </el-form-item>
        <el-form-item label="菜单icon样式" prop="icon">
          <el-input size="small" v-model="ruleForm.icon" placeholder="输入菜单图标样式"></el-input>
        </el-form-item>
        <el-form-item v-show="isUpdate" label="创建人：">{{createPeople}}</el-form-item>
        <el-form-item v-show="isUpdate" label="创建时间：">{{createTime}}</el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="success" @click="submitMenu('ruleForm')">保 存</el-button>
        <el-button size="small" type="danger" @click="cancleMenu('ruleForm')">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getserver,postserver } from '@/api/basicFunction'
import TreeTable from '@/components/tree-table/index.vue'
export default {
  name: 'department',
  components: { TreeTable },
  data() {
    return {
      columns: [
        {
          text: '菜单名称及操作',
          value: 'title'
        },
        {
          text: 'ID',
          value: 'id',
          width: 200
        },
        {
          text: '资源路径',
          value: 'url'
        },
        {
          text: '父节点id',
          value: 'pid'
        }
      ],
      menuType: [
        {
          label: '模块',
          type: '1'
        },
        {
          label: '链接',
          type: '2'
        },
        {
          label: '增加按钮',
          type: '3'
        },
        {
          label: '更新按钮',
          type: '4'
        },
        {
          label: '删除按钮',
          type: '5'
        },
        {
          label: '下载按钮',
          type: '6'
        },
        {
          label: '审核按钮',
          type: '7'
        },
        {
          label: '其他',
          type: '99'
        }
      ],
      tableData: [],
      isUpdate: false,
      ismodelMenu: false,
      createPeople: '',
      createTime: '',
      choiceArr: [],
      modelMenusList: [],
      menuVisible: false,
      title: '新增菜单',
      pid: 0,
      userId: '',
      removeIds: [],
      ruleForm: {
        name: '',
        menuparas: '',
        menuType: '',
        url: '',
        icon: '',
        level:''
      },
      rules: {
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' }
        ],
        menuType: [
          { required: true, message: '请选择菜单类型', trigger: 'change' }
        ]
      },
      menuSerData: '',
      hasAdd: false,
      hasDel: false,
      hasUpdate: false,
      addTitle: '新增',
      updateTitle: '修改',
      delTitle: '删除'
    }
  },
  mounted() {
    this.getMenuList()
    this.getJur()
  },
  methods: {
    getJur() {
      const self = this
      self.$store.dispatch('Juage', self.$store.clickMenuId).then(res => {
        if (res.code == '200') {
          res.data.forEach(item => {
            if (item.type == '3') {
              self.hasAdd = true
              self.addTitle = item.title
            }
            if (item.type == '5') {
              self.hasDel = true
              self.delTitle = item.title
            }
            if (item.type == '4') {
              self.hasUpdate = true
              self.updateTitle = item.title
            }
          })
        } else if (res.code !== '507') {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    getMenuList() {
      postserver({}, '/sysPermission/getAllMenuTree').then(res => {
      	console.log(res,'menu')
        if (res.code == '200') {
          this.tableData = res.data
          console.log(this.tableData,'menu12')
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    choice(val) {
      this.choiceArr = val
      this.removeIds = []
      val.forEach(item => {
        this.removeIds.push(item.id)
      })
    },
    handleClose() {
    	this.resetForm();
      this.menuVisible = false
    },
    addLine() {
      const self = this
      if (self.choiceArr.length && self.choiceArr.length > 1) {
        self.$message({
          type: 'info',
          message: '请只选择一个节点作为上级菜单增加菜单！'
        })
      } else if (self.choiceArr.length && self.choiceArr.length === 1) {
        self.title = self.addTitle
        self.ismodelMenu = false
        let modelMenusId = ''
        if(self.choiceArr[0].title =="模块基础信息"){
        		self.ismodelMenu = true
        		getserver({}, '/md/getAll').then(res => {
			        if (res.code == '200') {
			        	for(let i=0;i<res.data.length;i++){
			        		if(!res.data[i].description){
			        			res.data[i].description = '默认值'+i
			        		}
			        	}
			          self.modelMenusList = res.data
			          console.log(self.modelMenusList,'modelmenu')
			        } else {
			          this.$message({
			            type: 'error',
			            message: res.message
			          })
			        }
			      })
        	}
        self.menuVisible = true
        self.isUpdate = false
        self.pid = self.choiceArr[0].id
        self.ruleForm.level=self.choiceArr[0].level+1
      } else {
        this.$confirm('是否确认以根节点作为父节点添加菜单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          self.title = self.addTitle
          self.menuVisible = true
          self.isUpdate = false
          self.pid = 0
          self.ruleForm.level=1
        })
      }
    },
    submitMenu(formName) {
      const self = this
      self.$refs[formName].validate((valid) => {
        if (valid) {
          const para = {
            title: self.ruleForm.name,
            pid: self.pid,
            type: self.ruleForm.menuType,
            url: self.ruleForm.url,
            level:self.ruleForm.level,
            icon: self.ruleForm.icon ? self.ruleForm.icon : 'dashboard'
            // icon: self.ruleForm.menuType === 'Module' ? 'system' : self.ruleForm.icon
          }
          if (self.ruleForm.menuType === 'page_add') {
            para.functionname = 'add'
          } else if (self.ruleForm.menuType === 'page_update') {
            para.functionname = 'update'
          } else if (self.ruleForm.menuType === 'page_del') {
            para.functionname = 'del'
          }
          
          if (!self.isUpdate) {
            postserver(para, '/sysPermission/add').then(res => {
              if (res.code == '200') {
                self.$message({
                  type: 'success',
                  message: res.message
                })
                self.getMenuList()
              } else {
                self.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
          } else {
            para.id = self.userId
            postserver(para, '/sysPermission/update').then(res => {
            	console.log(res.code,'menuUpdate')
              if (res.code == '200') {
                self.$message({
                  type: 'success',
                  message: res.message
                })
                self.getMenuList();
                this.resetForm();
              } else {
                self.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
          }
          self.menuVisible = false
          self.$refs[formName].resetFields()
        }
      })
    },
    cancleMenu(formName) {
      this.menuVisible = false
      this.$refs[formName].resetFields()
    },
    removeLine() {
      const self = this
      if (self.choiceArr.length) {
        for (let i = 0; i < self.choiceArr.length; i++) {
          if (self.choiceArr[i].children.length) {
            self.$alert('您选择的菜单包含下级菜单，请先删除掉所有下级菜单后再进行该操作！', '系统提示', {
              confirmButtonText: '确定',
              callback: action => {}
            })
            break
          } else {
            self.$confirm('确定要删除所选择的菜单吗?', '信息确认', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              getserver({ ids: self.removeIds.toString() }, '/sysPermission/delete').then(res => {
                self.$message({
                  type: 'success',
                  message: res.message
                })
                self.getMenuList()
              })
            }).catch(() => {
              self.$message({
                type: 'info',
                message: '已取消删除'
              })
            })
          }
        }
      } else {
        self.$message({
          type: 'info',
          message: '请先选择需要删除的菜单！'
        })
      }
    },
    changeLine() {
      const self = this
      if (self.choiceArr.length && self.choiceArr.length === 1) {
        self.title = self.updateTitle
        self.menuVisible = true
        self.isUpdate = true
        getserver({ id: self.choiceArr[0].id }, '/sysPermission/info').then(res => {
          if (res.code == '200') {
            self.userId = res.data.id
            self.pid = res.data.pid
            self.ruleForm.name = res.data.title
	          self.menuType.forEach(item => {
		          if (item.type == res.data.type) {
		            self.ruleForm.menuType = String(item.type)
		          }
		        })
            self.ruleForm.url = res.data.url
            self.ruleForm.icon = res.data.icon
            self.createPeople = res.data.createName
            self.ruleForm.level = res.data.level
            self.createTime = res.data.createTime ? res.data.createTime.substring(0, 10) : ''
          }
        })
      } else {
        self.$message({
          type: 'info',
          message: '请只选择一个需要修改的菜单！'
        })
      }
    },
    findLine() {
      const para = { keywords: this.menuSerData }
      postserver(para, '/sysPermission/getAllMenuTree').then(res => {
        if (res.code == '200') {
          this.tableData = res.data
          console.log(this.tableData,'menu1')
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    resetForm(){
    	this.ruleForm.name = '';
      this.ruleForm.menuType = '';
      this.ruleForm.url = '';
      this.ruleForm.icon = '';
      this.ruleForm.level = '';
      this.ruleForm.menuparas = '';
    },
    sletMenuName(val){
    	this.modelMenusList.forEach(item => {
    		if(val == item.description){
    			this.ruleForm.menuparas = 'mdId='+item.mdId+'/mdType='+item.mdType;
    		}
    	})
    }
  }
}
</script>
<style scoped>
.btn-group{
  margin-bottom: 15px;
}
</style>

